package com.liu.dw.service.word;

import com.liu.dw.mapper.word.WordMapper;
import com.liu.dw.vo.word.Wdoument;
import com.liu.dw.vo.word.Wimage;
import com.liu.dw.vo.word.Wtable;
import com.liu.dw.vo.word.Wtext;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @version 1.0
 * @author： LiuWeiGang
 * @date： 2021-12-03 16:52
 */

@Service
public class WordServiceimpl implements WordService{

    @Autowired
    private WordMapper wordMapper;
    /**
     * 解析word文档
     * @param file
     */
    @Override
    public void uploadFile(MultipartFile file) throws IOException {
        Map<Integer,String> wordMap = new LinkedHashMap();//创建一个map对象存放word中的内容
        String textFileName=file.getOriginalFilename();
        String suffix = textFileName.substring(textFileName.lastIndexOf("."));
        //存入数据库的路径
        String pathfile = "/Users/liuweigang/Documents/临时文件/word/docx/d";
        byte[] bytes = file.getBytes();
        FileOutputStream textword = new FileOutputStream(pathfile + textFileName);
        textword.write(bytes);
        //向数据库中存入当前资源的路径
        String er = pathfile  + textFileName;
        //存放到用户ID中
        String fileName=file.getOriginalFilename();
        String replace = fileName.replace(".", ",");
        String[] split = replace.split(",");
        String s = split[0];
        //将上传的文件资源存入数据库
        Wdoument wdoument = new Wdoument();
        wdoument.setWpath(er);
        wdoument.setWname(textFileName);
        wdoument.setUserid(s);
        wordMapper.importWord(wdoument);

        //解析word中
        try {
            File uFile = new File("tempFile.docx");
            if (!uFile.exists()) {
                uFile.createNewFile();
            }
            //判断如果是 .docx 的文件解析
            if (suffix.endsWith(".docx")) {
                //解析文件中的文字
                FileCopyUtils.copy(file.getBytes(), uFile);//复制文件内容
                OPCPackage opcPackage = POIXMLDocument.openPackage("tempFile.docx");//包含所有POI OOXML文档类的通用功能，打开一个文件包。
                XWPFDocument document = new XWPFDocument(opcPackage);//使用XWPF组件XWPFDocument类获取文档内容
                List<XWPFParagraph> paras = document.getParagraphs();
                int i = 1;
                for (XWPFParagraph paragraph : paras) {
                    String words = paragraph.getText();
                    //将第几行和每行的数据存到map中
                    wordMap.put(i, words);
                    i++;
                }
                 //查询资源表中文档的ID；
                Wdoument douUserId = wordMapper.getDouUserId(textFileName);
                Integer zyid = douUserId.getId();
                Set<Map.Entry<Integer, String>> entries = wordMap.entrySet();
                Wtext wtext = new Wtext();
                for (Map.Entry<Integer, String> entry : entries) {
                    Integer key = entry.getKey();
                    String value = entry.getValue();
                    wtext.setTre(value);
                    wtext.setWnum(key);
                    wtext.setWdoumentId(zyid);
                    wordMapper.word(wtext);
                }

                //解析word2007中的图片
                List<XWPFPictureData> allPictures = document.getAllPictures();
                String imagePath = "/Users/liuweigang/Documents/临时文件/word/image/i";
                for (XWPFPictureData picture : allPictures) {
                    byte[] by = picture.getData();
                    FileOutputStream stream1 = new FileOutputStream(imagePath +  picture.getFileName());
                    stream1.write(by);
                    //向数据库中存入图片的完整路径
                    String path =  imagePath + picture.getFileName();
                    Wimage wimage = new Wimage();
                    wimage.setImpath(path);
                    wimage.setIms(by);
                    wimage.setWdoumentId(zyid);
                    wordMapper.image(wimage);
                }

                //解析word2007中的表格
                Iterator<XWPFTable> its = document.getTablesIterator();
                String[] strings = new String[4];
                Map<Integer,String> stringMap = new HashMap<>();
                String ns = "";
                int dfs = 0;
                int ind = 0;
                while (its.hasNext()){
                    ind++;
                    XWPFTable table = (XWPFTable) its.next();
                    //行
                    int rcount = table.getNumberOfRows();
                    for (int ix = 0; ix < rcount; ix++){
                        XWPFTableRow row = table.getRow(ix);
                        //列
                        List<XWPFTableCell> cells = row.getTableCells();
                        int len = cells.size();
                        for(int j = 0;j < len;j++){
                            XWPFTableCell xc = cells.get(j);
                            String sc = xc.getText();
                            strings[j] = sc;
                        }
                        StringBuffer sb = new StringBuffer();
                        for(int jd = 0; jd < strings.length; jd++){
                            sb. append(strings[jd]);
                        }
                        ns = sb.toString();
                        dfs++;
                        stringMap.put(dfs,ns);
                    }
                    Set<Map.Entry<Integer, String>> entries1 = stringMap.entrySet();
                    for (Map.Entry<Integer,String> entry: entries1) {
                        Integer key = entry.getKey();
                        String value = entry.getValue();
                        System.out.println("第"+key+"行"+","+value);
                        Wtable wtable = new Wtable();
                        wtable.setTared(value);
                        wtable.setTnum(key);
                        wtable.setWdocumentid(zyid);
                        wordMapper.table(wtable);
                    }
                }
                /**
                 * 解析word 2003中的文字
                 */
            }else if (suffix.endsWith(".doc")){
                Map<Integer,String> word = new LinkedHashMap();//创建一个map对象存
               //解析word2003版本中的文字
                InputStream fis = file.getInputStream();
                WordExtractor wordExtractor = new WordExtractor(fis);//使用HWPF组件中WordExtractor类从Word文档中提取文本或段落
                int i=1;
                for(String words : wordExtractor.getParagraphText()){//获取段落内容
                    word.put(i,words);
                    i++;
                }
                //查询资源表中文档的ID；
                Wdoument douUserId = wordMapper.getDouUserId(textFileName);
                Integer zid = douUserId.getId();
                Set<Map.Entry<Integer, String>> entries = word.entrySet();
                for (Map.Entry<Integer, String> entry: entries) {
                    Integer key = entry.getKey();
                    String value = entry.getValue();
                    Wtext wt = new Wtext();
                    wt.setTre(value);
                    wt.setWnum(key);
                    wt.setWdoumentId(zid);
                    wordMapper.word(wt);
                }

                // 处理doc格式 即office2003版本的表格
                POIFSFileSystem pfs = new POIFSFileSystem(fis);
                HWPFDocument hwpf = new HWPFDocument(pfs);
                String[] sword2003 = new String[4];
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator it = new TableIterator(range);
                // 迭代文档中的表格
                // 如果有多个表格只读取需要的一个 set是设置需要读取的第几个表格，total是文件中表格的总数
                int set = 1, total = 4;
                int num = set;
                for (int ii = 0; ii < set-1; ii++) {
                    it.hasNext();
                    it.next();
                }
                while (it.hasNext()) {
                    Table tb = (Table) it.next();
                    System.out.println("这是第" + num + "个表的数据");
                    //迭代行，默认从0开始,可以依据需要设置i的值,改变起始行数，也可设置读取到那行，只需修改循环的判断条件即可
                    for (int ix = 0; ix < tb.numRows(); ix++) {
                        TableRow tr = tb.getRow(ix);
                        //迭代列，默认从0开始
                        for (int j = 0; j < tr.numCells(); j++) {
                            TableCell td = tr.getCell(j);//取得单元格
                            //取得单元格的内容
                            for(int k = 0; k < td.numParagraphs(); k++){
                                Paragraph para = td.getParagraph(k);
                                String sc = para.text();
                                sword2003[k] = sc;
                            }
                        }
                    }
                }
            }
         }catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }
}
